﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Web;
using System.Data;
using WFServiceContract;
using WebKpiPage.Data.GongdanMgr;
using Model;
namespace WebKpiPage.BLL.GongdanMgr
{
    public class WFGongdanMgr
    {
        public static int requestDayNums = 0;
        private static WFGongdanRecord AddWFGongdanRecord(string description, string activityId,
            Guid gongdanId, Guid sendId, Guid recUserId, string signRemark, Guid instanceId, GongdanStatus status, int workflowId, ref Guid wfGongdanId)
        {
            WFGongdanRecord record = new WFGongdanRecord();
            record.ActivityDescription = description;
            record.ActivityId = activityId;
            record.FK_工单表_ID = gongdanId;
            record.ID = Guid.NewGuid();
            record.FK_RecUser_ID = recUserId;
            record.FK_SenderUser_ID = sendId;
            record.SignRemark = signRemark;
            record.WorkflowInstanceId = instanceId;
            
            record.FK_WF_工单状态ID = (int)status;//待处理工单
            record.WorkflowId = workflowId;
            record.J记录日期 = DateTime.Now;
            record.FK_Type_ID = 1;
            wfGongdanId = record.ID;
            int rtn = WebKpiPage.Data.GongdanMgr.GongdanMgrCls.AddWFGongDanRecord(record, "ADD");
            if (rtn > 0)
            {
                return record;
            }
            return null;

        }
        /// <summary>
        /// 添加工单处理记录
        /// </summary>
        /// <param name="instanceId"></param>
        /// <param name="userId"></param>
        /// <param name="subject"></param>
        /// <param name="isRead"></param>
        /// <param name="isDel"></param>
        /// <param name="wfId"></param>
        private static int AddDelGongdanRecord(Guid instanceId, Guid sendId, Guid recUserId, string subject, int isRead, int isDel, Guid wfId)
        {
            GongDanDelRecord gdR = new GongDanDelRecord();
            gdR.ID = Guid.NewGuid();
            gdR.WF_Instance_ID = instanceId;
            gdR.FK_RecUser_ID = recUserId;
            gdR.FK_SenderUser_ID = sendId;
            gdR.主题 = subject;
            DateTime? now = null;
            gdR.C处理日期 = now;
            gdR.J接收日期 = DateTime.Now;
            gdR.S是否已读 = isRead;
            gdR.S是否已处理 = isDel;
            gdR.FK_WF_工单记录表_ID = wfId;
            return WebKpiPage.Data.GongdanMgr.GongdanMgrCls.AddGongDanRecord(gdR);
        }
        public static bool Start(string gongdanId, string userId, ref WFGongdanRecord record)
        {
            if (gongdanId != "")
            {
                try
                {
                    StateActivity currentState;
                    Guid instanceId = WFWorkHelper.StartMyWorkflow(typeof(WorkflowLibrary.GongdanProject));

                    HttpApplicationState application = HttpContext.Current.Application;

                    WFGongdan examineService = (application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime).GetService<WFGongdan>();
                    ManualWorkflowSchedulerService scheduler = (application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime).GetService<ManualWorkflowSchedulerService>();
                    //获取当前状态机的状态
                    currentState = WFWorkHelper.GetCurrentState(instanceId);

                    examineService.RaiseEvent("EveOK", instanceId);

                    //启动工作流
                  //  examineService.RaiseEvent("eveOK", InstanceId);
                    scheduler.RunWorkflow(instanceId);

                    //获取当前状态机的状态
                    currentState = WFWorkHelper.GetCurrentState(instanceId);
                    Guid wfGongdanId = Guid.Empty;
                    //写工单记录表
                    record = AddWFGongdanRecord(currentState.Description, currentState.Name, new Guid(gongdanId)
                    , Guid.Empty, new Guid(userId), "系统派单", instanceId, GongdanStatus.系统派单, 1, ref  wfGongdanId);
                    ///MT_工单处理记录表
                    AddDelGongdanRecord(instanceId, Guid.Empty, new Guid(userId), "系统派单", 0, 0, wfGongdanId);
                    return true;
                }
                catch (System.Exception ex)
                {
                    return false;
                }
            }
            return false;
        }

        private static bool CheckEvent(string eventName, Guid instanceId, string selectEventDriven)
        {
            bool flag = false;
            StateActivity state = WFWorkHelper.GetCurrentState(instanceId);

            if (state.Activities[selectEventDriven] is EventDrivenActivity)
            {
                EventDrivenActivity edact = (EventDrivenActivity)state.Activities[selectEventDriven];
                if (edact.EnabledActivities[0] is HandleExternalEventActivity)
                {
                    HandleExternalEventActivity hee = (HandleExternalEventActivity)edact.EnabledActivities[0];
                    if (hee.EventName.ToLower().Equals(eventName) == true)
                    {
                        flag = true;
                    }
                }
            }
            return flag;
        }

        private static string GetEventName(Guid instanceId, string selectEventDriven)
        {
            string sflag = string.Empty;
            StateActivity state = WFWorkHelper.GetCurrentState(instanceId);
            if (state.Activities[selectEventDriven] is EventDrivenActivity)
            {
                EventDrivenActivity edact = (EventDrivenActivity)state.Activities[selectEventDriven];
                if (edact.EnabledActivities[0] is HandleExternalEventActivity)
                {
                    HandleExternalEventActivity hee = (HandleExternalEventActivity)edact.EnabledActivities[0];
                    sflag = hee.EventName;
                }
            }
            return sflag;
        }

        public static int PingGuFankui(GongDanProj proj, string eventValue)
        {
           // proj.DelwithId, proj.WorkflowInstanceId, proj.DelwithMan, proj.FK_User_责任人, proj.ID, proj.ActivityId
            Guid delwithID=proj.DelwithId;
             Guid instanseID=proj.WorkflowInstanceId;
            Guid userId=proj.DelwithMan;
            Guid nextUserId=proj.FK_User_责任人;
            Guid gongdanID=proj.ID;
            string activityId = proj.ActivityId;
            StateActivity currentStateNext;

            StateActivity currentStateNow = WFWorkHelper.GetCurrentState(instanseID);

            //HttpApplicationState application = HttpContext.Current.Application;
            //WorkflowRuntime workflowRuntime = application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime;

            //WorkflowInstance instance = workflowRuntime.GetWorkflow(instanseID);
            //instance.Load();

            BeginWorkFlow(eventValue, instanseID);
            try
            {
                currentStateNext = WFWorkHelper.GetCurrentState(instanseID);
               
            }
            catch
            {
                throw new Exception("Here");
            }
            GongdanStatus status = GongdanStatus.defult;
            string remark = "";
            #region 反馈状态
            if (currentStateNow.Name.ToLower().Equals("fankuistate"))
            {
                if (currentStateNext.Name.ToLower() == "wyzgstate" && eventValue.ToLower().Equals("evetimeout"))
                {
                    //超时T1，通知网优主管
                    status = GongdanStatus.超时T1;
                    remark = "超时T1，通知网优主管";
#warning               //未发邮件
                }
                else if (currentStateNext.Name.ToLower() == "wyzrstate" && eventValue.ToLower().Equals("evetimeout"))
                {
                    //超时T2，通知网优主任
                    status = GongdanStatus.超时T2;
                    remark = "超时T1，通知网优主任";
#warning               //未发邮件
                }
                else if (eventValue.ToLower().Equals("eveshqysh"))
                {
                    //申请延期
                    status = GongdanStatus.申请延期;
                    remark = "申请延期";

                }
                else if (eventValue.ToLower().Equals("evecontinue"))
                {
                    //继续指派
                    status = GongdanStatus.转派;
                    remark = "转派";

                }
                else if (eventValue.ToLower().Equals("evereject"))
                {
                    //退回
                    nextUserId = proj.SendmanID;
                    status = GongdanStatus.打回;
                    remark = "退回";
                }
                else if (eventValue.ToLower().Equals("evetijiao"))
                {
                    //提交
                    status = GongdanStatus.已处理;
                    remark = "提交";
                    nextUserId = new Guid();
                }
            }
            #endregion
            #region 已经处理状态
            else if (currentStateNow.Name.ToLower().Equals("chulistate"))
            {
                if (currentStateNext.Name.ToLower() == "wyzgstate")
                {
                    //升级到网优主管
                    status =GongdanStatus.升级1次;
                    remark = "升级一次，升级到网优主管";

                    //未发邮件 
#warning
                }
                else if (currentStateNext.Name.ToLower() == "closestate")
                {
                    //关闭
                    status = GongdanStatus.已关闭;
                    remark = "关闭";
                    nextUserId = new Guid();
                }
            }
            #endregion
            #region   网优主管状态
            else if (currentStateNow.Name.ToLower().Equals("wyzgstate") == true)
            {
                if (currentStateNext.Name.ToLower() == "wyzrstate" && eventValue.ToLower().Equals("evewyzgpgok"))
                {
                    //升级到网优主任
                    status = GongdanStatus.升级2次;
                    remark = "升级到网优主任";
                    //未发邮件 
#warning
                }
                else if (currentStateNext.Name.ToLower() == "wyzrstate" && eventValue.ToLower().Equals("evetimeout2"))
                {
                    // 超时T2，通知网优主任
                    status = GongdanStatus.超时T2;
                    remark = "超时T2，通知网优主任";
                    //未发邮件 
#warning
                }
                else if (currentStateNext.Name.ToLower() == "closestate")
                {
                    //关闭
                    status = GongdanStatus.已关闭;
                    remark = "关闭";
                    nextUserId = new Guid();
                }
                else if (eventValue.ToLower().Equals("evewyzgstatetijiao"))
                {
                    //  网优主管状态提交
                    status = GongdanStatus.已处理;
                    remark = "已处理";
                    nextUserId = new Guid();
                }
                else if (eventValue.ToLower().Equals("evewyzgcontinue"))
                {
                    // 网优主管状态转派
                    status = GongdanStatus.转派;
                    remark = "网优主管状态转派";
                }
                else if (eventValue.ToLower().Equals("evewyzgreject"))
                {
                    // 网优主管状态打回
                    status = GongdanStatus.打回;
                    nextUserId = proj.SendmanID;
                    remark = "网优主管状态转派";
                }
                else if (eventValue.ToLower().Equals("everejectysh"))
                {
                    //  网优主管拒绝延时处理
                    status = GongdanStatus.反对延期;
                    nextUserId = proj.SendmanID;
                    remark = "网优主管拒绝延时处理";
                }
                else if (eventValue.ToLower().Equals("eveagreeysh"))
                {
                    // 网优主管同意延时处理
                    status = GongdanStatus.同意延期;
                    nextUserId = proj.SendmanID;
                    remark = "网优主管同意延时处理";
                }
            }
            #endregion
            #region   网优主任状态
            else if (currentStateNow.Name.ToLower().Equals("wangyouzhurenstate") == true)
            {
                if (eventValue.ToLower().Equals("evewyzrstatetijiao"))
                {
                    status = GongdanStatus.已处理;//EveWYZRStateTijiao  EveWYZRContinue  EveWYZRReject
                    remark = "已处理";
                    nextUserId = new Guid();
                    //未发邮件 
#warning
                }
                else if (eventValue.ToLower().Equals("evewyzrcontinue"))
                {
                    status = GongdanStatus.转派;
                    remark = "网优主任状态转派";
                }
                else if (eventValue.ToLower().Equals("evewyzrreject"))
                {
                    nextUserId = proj.SendmanID;
                    status = GongdanStatus.打回;
                    remark = "网优主任状态打回";
                }
            }
            #endregion
            proj.FK_WF_工单当前状态=(int)status;
            proj.Y优化记录 =";\r\n"+DateTime.Now.ToString()+ remark;
            GongdanMgrCls.UpdateGongdanRecordWf(proj);
            UpdateGongdanDelwith(status, delwithID, instanseID, remark, userId);
            return AddModifyWf(currentStateNext.Description, currentStateNext.Name, gongdanID, userId, nextUserId, remark, instanseID, status);
        }
        /// <summary>
        /// 添加处理记录
        /// 添加工作流记录
        /// 更新状态
        /// </summary>
        /// <param name="description"></param>
        /// <param name="activityId"></param>
        /// <param name="gongdanId"></param>
        /// <param name="sendId"></param>
        /// <param name="nextUser"></param>
        /// <param name="signRemark"></param>
        /// <param name="instanceId"></param>
        /// <param name="status"></param>
        private static int AddModifyWf(string description, string activityId,
           Guid gongdanId, Guid sendId, Guid nextUser, string signRemark, Guid instanceId, GongdanStatus status)
        {
            if (status == GongdanStatus.同意延期 || status == GongdanStatus.反对延期 || status == GongdanStatus.申请延期)
            {
                GongDanRequest gdr = new GongDanRequest();
                if (status == GongdanStatus.申请延期)
                {
                    gdr.RequestMan = sendId;
                    gdr.RequestDayNums = requestDayNums;
                    gdr.RequestTime = DateTime.Now;
                }
                else
                {
                  
                    gdr.AnswerTime = DateTime.Now;
                    gdr.AnswerMan = sendId;
                    gdr.IsAgree = status == GongdanStatus.同意延期 ? true : false;
                   
                    gdr.RequestDayNums = requestDayNums;
                    gdr.RequestMan = sendId;
                }
                gdr.GongdanID = gongdanId;
                GongdanMgrCls.EditGongdanRequest(gdr);
                

            
            }
        
#warning 还需要增加修改处理记录表  改为已经处理：（1：分析人员的提交，2：其他人员的回复、转派、打回）。 
#warning 超时的，升级的原处理修改状态
            Guid wfGongdanId = Guid.Empty;
            WFGongdanRecord wfRd = AddWFGongdanRecord(description, activityId, gongdanId, sendId, nextUser, "", instanceId, status, 1, ref  wfGongdanId);
            if (wfRd != null)
            {
             
                int isRead = 0;
                int isDeal = 0;
                if (status==GongdanStatus.已处理)
                {
                    isRead = 1;
                    isDeal = 1;
                }
                return AddDelGongdanRecord(instanceId, sendId, nextUser, "", isRead, isDeal, wfGongdanId);
            }
            return -1;
        }
        /// <summary>
        ///  更新处理记录
        /// </summary>
        /// <param name="status"></param>
        /// <param name="delwithId"></param>
        /// <param name="instanseID"></param>
        /// <param name="remark"></param>
        /// <param name="gongdanID"></param>
        /// <param name="sendUserId"></param>
        /// <param name="recUserId"></param>
        /// <returns></returns>
        private static bool UpdateGongdanDelwith(GongdanStatus status,Guid delwithId,Guid instanseID,
            string remark,Guid sendUserId)
        {
            if (status == GongdanStatus.已处理 || status == GongdanStatus.转派 || status == GongdanStatus.打回 )
            {
               //修改自己的处理记录为已处理
                return GongdanMgrCls.UpdateGongdanDelwith(delwithId, instanseID, remark, sendUserId,0);
            }
            else if ( status == GongdanStatus.超时T1|| status == GongdanStatus.超时T2 || status == GongdanStatus.升级1次 || status == GongdanStatus.升级2次)
            {
                //更新原处理人的记录为最新的状态
                return GongdanMgrCls.UpdateGongdanDelwith(delwithId, instanseID, remark, sendUserId,1);
            }
            else if (status == GongdanStatus.同意延期 || status == GongdanStatus.反对延期)
            {
                //修改自己的处理记录和提交人的记录为已处理
                return GongdanMgrCls.UpdateGongdanDelwith(delwithId, instanseID, remark, sendUserId, 2);
            }
           
            return false;
        }
        private static void BeginWorkFlow(string SelectValue, Guid instanseID)
        {

            WFGongdan examineService = (HttpContext.Current.Application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime).GetService<WFGongdan>();
            ManualWorkflowSchedulerService scheduler = (HttpContext.Current.Application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime).GetService<ManualWorkflowSchedulerService>();


            HttpApplicationState application = HttpContext.Current.Application;
            WorkflowRuntime workflowRuntime = application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime;

          //  WorkflowInstance instance = workflowRuntime.GetWorkflow(instanseID);
          //  instance.Load();
           // instance.Start();
          //  instance.
            StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(HttpContext.Current.Application[WFWorkHelper.WorkflowRuntimeName] as WorkflowRuntime, instanseID);

            EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[SelectValue];
            HandleExternalEventActivity heva = (HandleExternalEventActivity)edact.EnabledActivities[0];

            examineService.RaiseEvent(heva.EventName, instanseID);
            scheduler.RunWorkflow(instanseID);
        }

    }
}
